// 配置弹窗逻辑
document.getElementById('config-btn').addEventListener('click', () => {
    fetch('/get-config')
        .then(response => response.json())
        .then(config => {
            document.getElementById('config-zentao-url').value = config.zentao_url;
            document.getElementById('config-xmind-url').value = config.xmind2testcase_url;
            document.getElementById('config-modal').style.display = 'block';
        });
});

// 保存配置
document.getElementById('config-save').addEventListener('click', () => {
    const newConfig = {
        zentao_url: document.getElementById('config-zentao-url').value,
        xmind2testcase_url: document.getElementById('config-xmind-url').value
    };

    fetch('/save-config', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify(newConfig)
    })
    .then(response => response.json())
    .then(data => {
        if (data.status === 'success') {
            alert('配置保存成功');
            location.reload(); // 刷新页面应用新配置
        } else {
            alert('保存失败: ' + (data.message || '未知错误'));
        }
    });
});

// 重置按钮
document.getElementById('config-reset').addEventListener('click', () => {
    fetch('/get-config')
        .then(response => response.json())
        .then(config => {
            document.getElementById('config-zentao-url').value = config.zentao_url;
            document.getElementById('config-xmind-url').value = config.xmind2testcase_url;
        });
});





// 文件上传相关逻辑
document.getElementById("csv_file_text").addEventListener("click", function() {
    document.getElementById("csv_file").click();
});
document.getElementById("choose-file").addEventListener("click", function() {
    document.getElementById("csv_file").click();
});
document.getElementById("csv_file").addEventListener("change", function(e) {
    document.getElementById("csv_file_text").value = e.target.files[0].name;
});

document.getElementById("import-form").addEventListener("submit", function(){
    localStorage.setItem("zentao_url", document.getElementById("zentao_url").value);
    localStorage.setItem("account", document.getElementById("account").value);
    localStorage.setItem("password", document.getElementById("password").value);
    localStorage.setItem("product_id", document.getElementById("product_id").value);
});

window.onload = function(){
    // 页面加载时先判断是否有用户修改后的默认禅道URL，若有则优先使用
    const defaultZentao = localStorage.getItem("default_zentao_url") || "http://127.0.0.1:80/zentao/api.php/v1";
    document.getElementById("zentao_url").value = localStorage.getItem("zentao_url") || defaultZentao;

    // 加载其他保存的字段
    const fields = ["account", "password", "product_id"];
    fields.forEach(field => {
        if(localStorage.getItem(field)){
            document.getElementById(field).value = localStorage.getItem(field);
        }
    });

    // 更新顶部链接的 URL（访问xmind2testcase工具），若用户已修改则用修改后的值
    const xmindUrl = localStorage.getItem("xmind2testcase_url") || "http://127.0.0.1:5001/";
    document.getElementById("xmind2testcase-link").href = xmindUrl;
};

/* ========== 配置弹窗逻辑 ========== */
var configBtn = document.getElementById("config-btn");
var configModal = document.getElementById("config-modal");
var configClose = document.getElementById("config-close");
var configCancel = document.getElementById("config-cancel");
var configSave = document.getElementById("config-save");
var configReset = document.getElementById("config-reset");

// 点击“修改配置”按钮时，弹出配置窗口，并填充当前配置值
configBtn.addEventListener("click", function(){
    var currentZentaoUrl = localStorage.getItem("default_zentao_url") || "http://127.0.0.1:80/zentao/api.php/v1";
    var currentXmindUrl = localStorage.getItem("xmind2testcase_url") || "http://127.0.0.1:5001/";
    document.getElementById("config-zentao-url").value = currentZentaoUrl;
    document.getElementById("config-xmind-url").value = currentXmindUrl;
    configModal.style.display = "block";
});

// 点击关闭按钮或“取消”按钮关闭弹窗
configClose.addEventListener("click", function(){
    configModal.style.display = "none";
});
configCancel.addEventListener("click", function(){
    configModal.style.display = "none";
});

// 点击“保存”按钮后，保存新配置并更新页面对应的默认值
configSave.addEventListener("click", function(){
    var newZentaoUrl = document.getElementById("config-zentao-url").value;
    var newXmindUrl = document.getElementById("config-xmind-url").value;
    if(newZentaoUrl) {
        localStorage.setItem("default_zentao_url", newZentaoUrl);
        var curInput = document.getElementById("zentao_url").value;
        if(!curInput || curInput === "http://127.0.0.1:80/zentao/api.php/v1") {
            document.getElementById("zentao_url").value = newZentaoUrl;
        }
    }
    if(newXmindUrl) {
        // 如果用户输入的 URL 没有 http:// 或 https:// 开头，则自动添加
        if (!newXmindUrl.startsWith("http://") && !newXmindUrl.startsWith("https://")) {
            newXmindUrl = "http://" + newXmindUrl;
        }
        localStorage.setItem("xmind2testcase_url", newXmindUrl);
        document.getElementById("xmind2testcase-link").href = newXmindUrl;
    }
    configModal.style.display = "none";
});

// 新增重置按钮的逻辑：点击后恢复为默认值
configReset.addEventListener("click", function(){
    document.getElementById("config-zentao-url").value = "http://127.0.0.1:80/zentao/api.php/v1";
    document.getElementById("config-xmind-url").value = "http://127.0.0.1:5001/";
});

// 点击弹窗外区域时关闭弹窗
window.onclick = function(event) {
    if (event.target == configModal) {
        configModal.style.display = "none";
    }
};
